#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include "irc.h"
#include "info.h"
#include "re.h"
#include "utils.h"
#include "mod.h"

int main(int argc, char **argv) {

   INFO *info;
   MOD *mod;
   RE *re;
   char match[255], dateout[15], *buffer;
   int i;

   info = OneGetInfo();
   OneConnect(info);

   re = (RE *) malloc(sizeof(RE));

   mod = modinit(info);

   while( info->alive == 1 ) {

      sleep(0.2);

      info->reciev = rsock(info->f);

      if(matcher("^PING (:.*)$",info->reciev, re)) {

         buffer = re_copy(re,1, info->reciev);
         ssock(info->fd, "PONG %s\r\n", buffer);
         free(buffer);

      }

      for(i=0;i<info->mods;i++)
         mod[i].init(info);

      if(matcher("^:([^ ]+)!([^ ]+)@[^ ]+ PRIVMSG ([^ ]+) :\\.remod$",info->reciev, re)) {

         struct sockaddr_in *s=(struct sockaddr_in *) malloc(sizeof(struct sockaddr_in));
         int fd,con;
         FILE *fp;

         memcpy(s, info->s, sizeof(info->s));
         fd = info->fd;
         con = info->con;
         fp = info->f;

         modend(info, mod);
         free(info);
         info = OneGetInfo();

         info->fd = fd; info->con = con; info->s = s; info->f = fp;
         info->reciev = strdup("Regenerating info for remod");

         system("make modules");
         free(mod);

         mod = modinit(info);

      }

      if(matcher("^ERROR :.*Link:",info->reciev, re)) info->alive = 0;

      if(argc != 2 && strcmp(argv[1], "-q") != 0) printf("%s\n",info->reciev);
      free(info->reciev);

   }

   modend(info, mod);

   printf("Exiting...\n");
   
}
